﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using MvcPrinciples.Logic;
using MvcPrinciples.Models;

namespace MvcPrinciples.Controllers
{
    public class PersonController : Controller
    {
        public ActionResult Index()
        {
            return View(DataProvider.GetStore.GetPersons());
        }

		public ActionResult AddPerson()
		{
			return View();
		}

		public ActionResult EditPerson(Guid id)
		{
			return View(DataProvider.GetStore.GetPerson(id));
		}

		public ActionResult AddPersonToList(Person person)
		{
			var imageFile = Request.Files["imageFile"];

			if (imageFile != null && imageFile.ContentLength > 0)
			{
				var imageId = Guid.NewGuid();
				imageFile.SaveAs(string.Format(Server.MapPath(string.Format("~/App_Data/{0}", imageId))));
				person.Image = new KeyValuePair<Guid, string>(imageId, imageFile.ContentType);
			}

			DataProvider.GetStore.AddPerson(person);
			return RedirectToAction("Index", "Person");
		}

		public ActionResult EditPersonInList(Person person)
		{
			var imageFile = Request.Files["imageFile"];

			if (imageFile != null && imageFile.ContentLength > 0)
			{
				var imageId = Guid.NewGuid();
				imageFile.SaveAs(string.Format(Server.MapPath(string.Format("~/App_Data/{0}", imageId))));
				person.Image = new KeyValuePair<Guid, string>(imageId, imageFile.ContentType);
			}

			DataProvider.GetStore.EditPerson(person);
			return RedirectToAction("Index", "Person");
		}

	    public ActionResult GetImage(Guid id, string type)
		{
			return File(Server.MapPath(string.Format("~/App_Data/{0}", id)), type);
		}

	    public ActionResult DownloadList()
	    {
			return File(DataProvider.GetStore.GetPersonsList(), "application/octet-stream", string.Format("{0}.txt", DateTime.Now.ToString("O")));
	    }
    }
}